use scraper::{Html, Selector};
use serde::{Deserialize, Serialize};

use crate::REQWEST_CLIENT;
use anyhow::{anyhow, Result};
/// 基金持仓
#[derive(Debug, Serialize, Deserialize)]
struct ApiData {
    content: String,
    arryear: Vec<u32>,
    curyear: Option<u32>,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct FundJjcc {
    pub report_date: String,
    pub title: String,
    pub data: Vec<FundJjccData>,
}

/// 序号	股票代码	股票名称	最新价	涨跌幅	相关资讯	占净值 比例	持股数（万股）	持仓市值（万元）
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct FundJjccData {
    pub serial_number: String,        // 序号
    pub stock_code: String,           // 股票代码
    pub stock_name: String,           // 股票名称
    pub related_news: String,         // 相关资讯
    pub net_value_ratio: String,      // 占净值比例
    pub holding_shares: String,       // 持股数（万股）
    pub holding_market_value: String, // 持仓市值（万元）
}

impl FundJjcc {
    /// 基金持仓 Referer: https://fundf10.eastmoney.com/ccmx_000001.html
    ///
    /// Data: https://fundf10.eastmoney.com/FundArchivesDatas.aspx?type=jjcc&code=000001&topline=1000&year=2021&month=3,6,9,12&rt=0.6337013513517491
    pub async fn fund_jjcc(_code: &str, _year: u32) -> Result<Vec<FundJjcc>> {
        // GET /FundArchivesDatas.aspx?type=jjcc&code=000001&topline=10&year=2009&month=12&rt=0.5142234771266505 HTTP/1.1
        // Accept: */*
        // Accept-Encoding: gzip, deflate, br
        // Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
        // Cache-Control: no-cache
        // Connection: keep-alive
        // Cookie: qgqp_b_id=d6299473145338f68687834ba37fa719; st_si=77687174285423; ASP.NET_SessionId=5ufgex2sjbo4p44lwytenq3s; searchbar_code=159834; AUTH_FUND.EASTMONEY.COM_GSJZ=AUTH*TTJJ*TOKEN; EMFUND0=01-29%2015%3A02%3A07@%23%24%u534E%u590F%u4E2D%u8BC1%u5168%u6307%u623F%u5730%u4EA7ETF@%23%24515060; EMFUND1=01-30%2014%3A41%3A22@%23%24%u534E%u6CF0%u67CF%u745E%u6D88%u8D39%u6210%u957F%u6DF7%u5408@%23%24001069; EMFUND2=01-30%2014%3A45%3A59@%23%24%u5E7F%u53D1%u6052%u751F%u6D88%u8D39%28QDII-ETF%29@%23%24159699; EMFUND3=01-30%2014%3A47%3A24@%23%24%u5357%u65B9%u7EA2%u5229%u4F4E%u6CE250ETF@%23%24515450; EMFUND4=01-31%2015%3A21%3A23@%23%24%u56FD%u8054%u4E2D%u8BC1%u7164%u70AD%u6307%u6570%28LOF%29A@%23%24168204; EMFUND5=02-02%2008%3A34%3A56@%23%24%u666F%u987A%u957F%u57CE%u652F%u67F1%u4EA7%u4E1A%u6DF7%u5408@%23%24260117; EMFUND6=02-02%2010%3A30%3A22@%23%24%u897F%u90E8%u5229%u5F97%u805A%u79BE%u6DF7%u5408A@%23%24007423; EMFUND7=02-26%2016%3A07%3A01@%23%24%u91D1%u9E70%u6DFB%u76C8%u7EAF%u503A%u503A%u5238A@%23%24003384; EMFUND8=02-27%2010%3A51%3A37@%23%24%u534E%u590F%u6210%u957F%u6DF7%u5408@%23%24000001; EMFUND9=02-27 13:53:07@#$%u534E%u6CF0%u67CF%u745E%u5357%u65B9%u4E1C%u82F1%u6052%u751F%u79D1%u6280%28QDII-ETF%29@%23%24513130; st_asi=delete; HAList=ty-0-159001-%u8D27%u5E01ETF%2Cty-0-000001-%u5E73%u5B89%u94F6%u884C%2Cty-0-161127-%u6807%u666E%u751F%u7269%u79D1%u6280LOF%2Cty-1-513130-%u6052%u751F%u79D1%u6280ETF%2Cty-0-300078-%u601D%u521B%u533B%u60E0%2Cty-0-300486-%u4E1C%u6770%u667A%u80FD%2Cty-1-513360-%u6559%u80B2ETF%2Cty-0-300478-%u676D%u5DDE%u9AD8%u65B0%2Cty-0-301589-N%u8BFA%u74E6%2Cty-1-603135-%u4E2D%u91CD%u79D1%u6280; st_pvi=47260449691882; st_sp=2024-01-12%2017%3A28%3A27; st_inirUrl=https%3A%2F%2Fwww.google.com.hk%2F; st_sn=723; st_psi=20240228151758316-113200301327-3226400255
        // Host: fundf10.eastmoney.com
        // Pragma: no-cache
        // Referer: https://fundf10.eastmoney.com/ccmx_000001.html
        // Sec-Fetch-Dest: script
        // Sec-Fetch-Mode: no-cors
        // Sec-Fetch-Site: same-origin
        // User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36
        // sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"
        // sec-ch-ua-mobile: ?0
        // sec-ch-ua-platform: "macOS"

        // Query String Parameters:
        //
        // type: jjcc
        // code: 000001
        // topline: 10
        // year: 2009
        // month: 3,6,9,12
        // rt: 0.5142234771266505

        let request_url = format!(
            "https://fundf10.eastmoney.com/FundArchivesDatas.aspx?type=jjcc&code=000001&topline=1000&year=2021&month=3,6,9,12&rt=0.6337013513517491");
        let response = REQWEST_CLIENT.get(request_url)
        .header(reqwest::header::ACCEPT, "*/*")
        .header(reqwest::header::ACCEPT_ENCODING, "gzip, deflate, br")
        .header(reqwest::header::ACCEPT_LANGUAGE, "zh-CN,zh;q=0.9,en;q=0.8")
        .header(reqwest::header::CACHE_CONTROL,"no-cache")
        .header(reqwest::header::CONNECTION,"keep-alive")
        // .header(reqwest::header::COOKIE, "qgqp_b_id=d6299473145338f68687834ba37fa719; st_si=77687174285423; AUTH_FUND.EASTMONEY.COM_GSJZ=AUTH*TTJJ*TOKEN; EMFUND0=01-16%2016%3A57%3A06@%23%24%u4E2D%u822A%u65B0%u8D77%u822A%u7075%u6D3B%u914D%u7F6E%u6DF7%u5408A@%23%24005537; EMFUND1=01-16%2017%3A04%3A53@%23%24%u91D1%u4FE1%u6D88%u8D39%u5347%u7EA7%u80A1%u7968A@%23%24006692; EMFUND2=01-16%2020%3A01%3A56@%23%24%u5357%u65B9%u4E0A%u8BC1380ETF@%23%24510290; EMFUND3=01-29%2015%3A02%3A07@%23%24%u534E%u590F%u4E2D%u8BC1%u5168%u6307%u623F%u5730%u4EA7ETF@%23%24515060; EMFUND4=01-30%2014%3A41%3A22@%23%24%u534E%u6CF0%u67CF%u745E%u6D88%u8D39%u6210%u957F%u6DF7%u5408@%23%24001069; EMFUND5=01-30%2014%3A45%3A59@%23%24%u5E7F%u53D1%u6052%u751F%u6D88%u8D39%28QDII-ETF%29@%23%24159699; EMFUND6=01-30%2014%3A47%3A24@%23%24%u5357%u65B9%u7EA2%u5229%u4F4E%u6CE250ETF@%23%24515450; EMFUND7=01-31%2015%3A21%3A23@%23%24%u56FD%u8054%u4E2D%u8BC1%u7164%u70AD%u6307%u6570%28LOF%29A@%23%24168204; EMFUND8=02-02%2008%3A34%3A56@%23%24%u666F%u987A%u957F%u57CE%u652F%u67F1%u4EA7%u4E1A%u6DF7%u5408@%23%24260117; EMFUND9=02-02 10:30:22@#$%u897F%u90E8%u5229%u5F97%u805A%u79BE%u6DF7%u5408A@%23%24007423; st_asi=delete; HAList=ty-1-513130-%u6052%u751F%u79D1%u6280ETF%2Cty-0-300078-%u601D%u521B%u533B%u60E0%2Cty-0-300486-%u4E1C%u6770%u667A%u80FD%2Cty-1-513360-%u6559%u80B2ETF%2Cty-0-300478-%u676D%u5DDE%u9AD8%u65B0%2Cty-0-301589-N%u8BFA%u74E6%2Cty-1-603135-%u4E2D%u91CD%u79D1%u6280%2Cty-0-000001-%u5E73%u5B89%u94F6%u884C%2Cty-0-002400-%u7701%u5E7F%u96C6%u56E2%2Cty-1-601127-%u8D5B%u529B%u65AF; st_pvi=47260449691882; st_sp=2024-01-12%2017%3A28%3A27; st_inirUrl=https%3A%2F%2Fwww.google.com.hk%2F; st_sn=438; st_psi=20240226102321941-113200301321-9024721593")
        .header(reqwest::header::HOST,"fundf10.eastmoney.com")
        .header(reqwest::header::PRAGMA, "no-cache")
        .header(reqwest::header::REFERER , "https://fundf10.eastmoney.com/ccmx_000001.html")
        .header(reqwest::header::USER_AGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36")
        .header("Sec-Ch-Ua", "\"Not A(Brand\";v=\"99\", \"Google Chrome\";v=\"121\", \"Chromium\";v=\"121\"")
        .header("Sec-Ch-Ua-Mobile", "?0")
        .header("Sec-Ch-Ua-Platform", "\"macOS\"")
        .header("Sec-Fetch-Dest", "empty")
        .header("Sec-Fetch-Mode", "cors")
        .header("Sec-Fetch-Site", "same-origin")
        .send()
        .await?;

        let body = response.text().await?;
        println!("*** body={}\n\n", body);

        let json_body = body
            .replace("var apidata=", "")
            .replace(";", "")
            .replace("content:", "\"content\":")
            .replace("arryear:", "\"arryear\":")
            .replace("curyear:", "\"curyear\":");
        println!("\n\njson_body: {:?}", json_body);

        let api_data: ApiData = serde_json::from_str(&json_body)?;

        println!("\n\napi_data= {:?}", api_data);

        Self::extract_data(&api_data.content)
    }

    fn extract_data(html: &str) -> Result<Vec<FundJjcc>> {
        let mut fund_jjccs = Vec::new();
        let document = Html::parse_document(html);
        // <div class="box">
        let div_box_selector = Selector::parse("div.box").map_err(|e| anyhow!(e.to_string()))?;
        for (_index, div_box) in document.select(&div_box_selector).enumerate() {
            let box_data = Self::extract_box_data(&div_box.html())?;
            fund_jjccs.push(box_data);
        }

        Ok(fund_jjccs)
    }

    fn extract_box_data(html: &str) -> Result<FundJjcc> {
        let mut fund_jjcc = FundJjcc {
            data: Vec::new(),
            ..Default::default()
        };
        let document = Html::parse_document(html);
        let title_selector =
            Selector::parse("h4 label.left").map_err(|e| anyhow!(e.to_string()))?;
        if let Some(element) = document.select(&title_selector).next() {
            fund_jjcc.title = element.text().collect::<String>().replace("&nbsp;", "");
        }

        let report_date_selector =
            Selector::parse("h4 label font").map_err(|e| anyhow!(e.to_string()))?;
        if let Some(element) = document.select(&report_date_selector).next() {
            fund_jjcc.report_date = element.text().collect::<String>().replace("&nbsp;", "");
        }

        // w782 comm tzxq t2
        let table_selector = Selector::parse("table.w782.comm.tzxq.t2 tbody tr")
            .map_err(|e| anyhow!(e.to_string()))?;
        let td_selector = &Selector::parse("td").map_err(|e| anyhow!(e.to_string()))?;
        let td_a_selector = &Selector::parse("td a").map_err(|e| anyhow!(e.to_string()))?;
        // <tr><th class="first">序号</th><th>股票代码</th><th>股票名称</th><th class="xglj">相关资讯</th><th>占净值<br>比例</th><th class="cgs">持股数<br>（万股）</th><th class="last ccs">持仓市值<br>（万元）</th></tr>
        // <tr><td>1</td><td><a href="//quote.eastmoney.com/unify/r/0.002821">002821</a></td><td class="tol"><a href="//quote.eastmoney.com/unify/r/0.002821">凯莱英</a></td><td class="xglj"><a href="//guba.eastmoney.com/interface/GetList.aspx?code=0.002821">股吧</a><a href="//quote.eastmoney.com/unify/r/0.002821">行情</a></td><td class="tor">3.76%</td><td class="tor">31.85</td><td class="tor">13,853.97</td></tr>
        for (_index, row) in document.select(&table_selector).enumerate() {
            let serial_number = row
                .select(td_selector)
                .nth(0)
                .map(|e| e.text().collect::<String>())
                .unwrap_or_default(); // 序号
            let stock_code = row
                .select(td_a_selector)
                .nth(0)
                .map(|e| e.text().collect::<String>())
                .unwrap_or_default(); // 股票代码
            let stock_name = row
                .select(td_a_selector)
                .nth(1)
                .map(|e| e.text().collect::<String>())
                .unwrap_or_default(); // 股票名称
            let related_news = row
                .select(td_a_selector)
                .nth(2)
                .map(|e| e.text().collect::<String>())
                .unwrap_or_default(); // 相关资讯
            let net_value_ratio = row
                .select(td_selector)
                .nth(4)
                .map(|e| e.text().collect::<String>())
                .unwrap_or_default(); // 占净值比例
            let holding_shares = row
                .select(td_selector)
                .nth(5)
                .map(|e| e.text().collect::<String>())
                .unwrap_or_default(); // 持股数（万股）
            let holding_market_value = row
                .select(td_selector)
                .nth(6)
                .map(|e| e.text().collect::<String>())
                .unwrap_or_default(); // 持仓市值（万元）

            let e_data = FundJjccData {
                serial_number,
                stock_code,
                stock_name,
                related_news,
                net_value_ratio,
                holding_shares,
                holding_market_value,
                ..Default::default()
            };
            fund_jjcc.data.push(e_data);
        }

        Ok(fund_jjcc)
    }
}

#[cfg(test)]
mod test {
    use crate::fund::fund_jjcc::FundJjcc;

    #[tokio::test]
    async fn test_fund_jjcc() {
        let result = FundJjcc::fund_jjcc("000001", 2021).await;

        // println!("result={:?}", result);

        assert_eq!(result.is_ok(), true);
        if let Ok(fund_jjccs) = result {
            println!(
                "\n\nfund_jjccs.first= {:?}\n",
                fund_jjccs.first().unwrap().data.first()
            );
        }
    }
}
